import { doFetch, getFetch, postFetch } from '@/utils/doFetch';
import {
  DesktopOutlined,
  LockOutlined,
  UserOutlined,
  WechatFilled,
} from '@ant-design/icons';
import {
  LoginForm,
  ProFormCheckbox,
  ProFormText,
} from '@ant-design/pro-components';
import { history, useModel } from '@umijs/max';
import { useAsyncEffect, useRequest } from 'ahooks';
import { Button, Tabs, theme } from 'antd';
import { useRef, useState, useEffect } from 'react';
import Zoom from 'react-reveal/Zoom';
import styles from './index.less';
import useWxCode from '@/utils/useWxCode';
import useCurrentUser from '@/utils/useCurrentUser';
import dayjs from 'dayjs';
function wxlogincode(state) {
  let obj = new WxLogin({
    self_redirect: false,
    id: 'login_container',
    appid: AppID,
    scope: 'snsapi_login',
    redirect_uri: encodeURIComponent(REDRIECT + "/#/user/login"),
    state: state,
    style: 'white',
    href: 'data:text/css;base64,LmltcG93ZXJCb3ggLnFyY29kZSB7d2lkdGg6IDEwMCU7IG1hcmdpbjogMHB4O2JvcmRlcjogbm9uZX0KLmltcG93ZXJCb3ggLnRpdGxlIHtkaXNwbGF5OiBub25lO30KLmltcG93ZXJCb3ggLmluZm8ge2Rpc3BsYXk6IG5vbmU7fQouc3RhdHVzX2ljb24ge2Rpc3BsYXk6IG5vbmV9Ci5pbXBvd2VyQm94IC5zdGF0dXMge3RleHQtYWxpZ246IGNlbnRlcjt9Cgo=',
  });
}

// function fixUrl(url) {
//   // 使用正则表达式提取IP、参数和哈希路由
//   const matches = url.match(/^([^?#]+)(\?[^#]*)?(#.*)?$/);
//   if (!matches) {
//     return url; // 如果匹配失败，返回原始 URL
//   }
//   const [, baseUrl, queryParams, hashRoute] = matches;
//   // 重新拼接 URL
//   let fixedUrl = baseUrl + '#';
//   if (hashRoute) {
//     fixedUrl += hashRoute.replace(/^#/, ''); // 去除哈希路由前的 #
//   }
//   if (queryParams) {
//     fixedUrl += '?' + queryParams.replace(/^\?/, ''); // 去除参数前的 ?
//   }
//   return fixedUrl;
// }

// // 修复 hash 路由 url
// function fixHashUrlAndJump() {
//   if (location.href.includes(`/?code`)) {
//     const currectpath = fixUrl(location.href);
//     location.href = currectpath;
//     return true;
//   } else {
//     return false;
//   }
// }

const Loginpage = ({ isin, setIsin, mode }) => {
  const formRef = useRef();
  const { getUser, currentUser, setInitialState } = useCurrentUser();

  const [loginType, setLoginType] = useState('account');
  const [hascode, setHascode] = useState(true);

  const {
    token: { colorText },
  } = theme.useToken();

  //接口调用完成后处理逻辑
  async function login(msg) {
    if (msg.code === 0) {
      localStorage.setItem('TOKENES', msg?.data?.data?.token);
      await getUser.runAsync();
      setIsin(false);
      history.push('/welcome');
    }
  }


  const { runAsync } = useRequest(doFetch, {
    manual: true,
    debounceWait: 1000,
  })

  //点击 form 登录
  const handleSubmit = async (values) => {
    if (loginType === 'account') {
      // 登录
      const msg = await runAsync({
        url: '/system/login',
        params: {
          account: values?.username,
          password: values?.password,
        },
      });
      if (values.autoLogin) {
        localStorage.setItem('UP', JSON.stringify(values));
      } else {
        localStorage.removeItem('UP');
      }
      await login(msg);
    } else {
    }
  };

  //填充记住密码的数据
  useEffect(() => {
    const up = localStorage.getItem('UP');
    if (up) {
      let ups = JSON.parse(up);
      formRef?.current?.setFieldsValue?.(ups);
    }
  }, []);

  // 扫码登录逻辑
  useWxCode(async (state, code, pathname) => {
    if (!code || !state) {
      setHascode(false);
      return;
    }
    setHascode(true);
    const token = localStorage.getItem('TOKENES');
    if (token || pathname !== '/user/login') {
      return;
    }
    let msg = await runAsync({
      url: '/system/wxLogin',
      params: { code, state },
    });
    await login(msg);
  })

  //打开微信登录二维码
  useAsyncEffect(async () => {
    if (loginType === 'wx') {
      const string = await getFetch({ url: '/wx/bind' });
      wxlogincode(string?.data?.data);
    }
  }, [loginType]);


  useEffect(() => {
    setInitialState(s => ({
      ...s,
      proList: [],
      myProList: [],
      drawerAll: {},
      curpro: {
        id: null,
      },
      activeUserIdList: [],
      updateSelect: '11',
      viewType: "step",
      selectedDate: dayjs(),
      kanbansparams: {
        projectTagIds: [],
        userIds: '',
        itemStatus: ''
      }
    }))
  }, []);

  return (
    !hascode && (
      <Zoom when={isin}>
        <div
          className="noline"
          style={{
            width: 400,
            maxWidth: 'calc(100vw - 16vw)',
            overflow: 'hidden',
            position: 'fixed',
            right: 0,
            left: 0,
            margin: 'auto',
            top: '20vh',
            marginTop: '-2%',
            zIndex: 9999,
            backgroundColor:
              mode === 'light' ? 'rgba(255,255,255,0.8)' : 'rgba(0,0,0,0.6)',
            borderRadius: 12,
            color: colorText,
            backdropFilter: 'blur(4px)',
            boxShadow: '0 0 80px rgba(0,0,0,0.1)',
          }}
        >
          <div
            style={{
              flex: 1,
              paddingBottom: 24,
            }}
          >
            <div className={styles.logo} style={{ color: '#F0F0F0' }}>
              <div
                style={{
                  color: colorText,
                  gap: 10,
                  padding: '16px 0px 12px 8px',
                }}
                className="column"
              >
                <b>TASKS 管理平台</b>
                <span style={{ opacity: 0.8, fontSize: 14 }}>
                  团队任务及进度实时跟踪
                </span>
              </div>
            </div>
            <LoginForm
              formRef={formRef}
              contentStyle={{
                minWidth: 200,
                maxWidth: '75vw',
                width: '100%',
              }}
              onFinish={async (values) => {
                await handleSubmit(values);
              }}
              submitter={
                loginType === 'wx'
                  ? false
                  : {
                    searchConfig: {
                      submitText: loginType === 'account' ? '登录' : '注册',
                    },
                  }
              }
            >
              {loginType === 'wx' ? (
                <div
                  className="columns"
                  style={{ justifyContent: 'center', alignItems: 'center' }}
                >
                  <span className="center" style={{ gap: 8, marginTop: 20 }}>
                    <WechatFilled style={{ color: '#1AAD19', fontSize: 17 }} />
                    使用微信扫一扫登录
                  </span>
                  <div
                    id="login_container"
                    style={{
                      width: '190px',
                      height: '190px',
                      margin: '12px auto 13px auto',
                    }}
                  ></div>
                  <span className="opacityani">
                    未绑定的微信号将自动创建账号
                  </span>
                </div>
              ) : (
                <>
                  <Tabs
                    activeKey={loginType}
                    onChange={(activeKey) => setLoginType(activeKey)}
                    items={[
                      {
                        key: 'account',
                        label: '登录',
                      },
                    ]}
                  ></Tabs>
                  {loginType === 'account' && (
                    <>
                      <ProFormText
                        name="username"
                        fieldProps={{
                          size: 'large',
                          prefix: <UserOutlined />,
                        }}
                        placeholder={'用户名'}
                        rules={[
                          {
                            required: true,
                            message: '请输入用户名!',
                          },
                        ]}
                      />
                      <ProFormText.Password
                        name="password"
                        fieldProps={{
                          size: 'large',
                          prefix: <LockOutlined />,
                        }}
                        placeholder={'密码'}
                        rules={[
                          {
                            required: true,
                            message: '请输入密码！',
                          },
                        ]}
                      />
                      <div
                        style={{
                          marginBottom: 24,
                        }}
                      >
                        <ProFormCheckbox noStyle name="autoLogin">
                          记住密码
                        </ProFormCheckbox>
                      </div>
                    </>
                  )}
                </>
              )}
            </LoginForm>
            <div className="center">
              <Button
                icon={
                  loginType === 'wx' ? (
                    <DesktopOutlined
                      style={{ color: '#000000', fontSize: 20 }}
                    />
                  ) : (
                    <WechatFilled style={{ color: '#1AAD19', fontSize: 22 }} />
                  )
                }
                type="text"
                size="large"
                onClick={() => {
                  setLoginType(loginType === 'wx' ? 'account' : 'wx');
                }}
              ></Button>
            </div>
          </div>
        </div>
      </Zoom>
    )
  );
};

export default Loginpage;
